<template>
  <el-form
    ref="loginFormRef"
    :model="loginForm"
    :rules="env.VITE_RELEASE_NAME === 'fendi' ? loginRules1 : loginRules2"
    size="large"
  >
    <el-form-item prop="username">
      <el-input class="inputDeep" v-model="loginForm.username" placeholder="请输入账号">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        class="inputDeep"
        v-model="loginForm.password"
        type="password"
        placeholder="请输入密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="verificationCode" v-if="env.VITE_RELEASE_NAME === 'fendi'">
      <div class="flx-default w100">
        <el-input class="inputDeep" v-model="loginForm.verificationCode" placeholder="验证码">
          <template #prefix>
            <i class="iconfont icon-yanzhengma" />
          </template>
        </el-input>
        <img class="yzm" @click="getDynamicCode()" :src="dynamicCode" />
      </div>
    </el-form-item>
    <!-- 测试环境记住密码 start😒-->
    <div v-if="isShowPassword">
      <el-row style="width: 100%" justify="end">
        <el-checkbox label="记住密码" v-model="isRemember" />
      </el-row>
    </div>
    <!-- 测试环境记住密码 end😒-->
  </el-form>
  <div class="login-btn">
    <el-button
      style="color: #ffffff"
      size="large"
      color="#ff6200"
      type="primary"
      :loading="loading"
      @click="login(loginFormRef)"
      :disabled="!propsData.animation"
    >
      登录
    </el-button>
  </div>
  <ChangePasswordDialog ref="dialogRef" />
</template>

<script setup lang="ts">
import { Login } from "@/api/interface";
import { getIdentify, loginApi } from "@/api/modules/login";
import { HOME_URL } from "@/config";
import { useTabsStore } from "@/stores/modules/tabs";
import { useUserStore } from "@/stores/modules/user";
import { getTimeState } from "@/utils";
import { ElNotification } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
// import { useDictStore } from "@/stores/modules/dicts";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
// import { UserFilled } from "@element-plus/icons-vue";
import { isOutDate } from "@/api/modules/system";
import ChangePasswordDialog from "@/layouts/components/Header/components/PasswordDialog.vue";
import type { ElForm } from "element-plus";
import md5 from "js-md5";

interface Props {
  animation: boolean;
}

// <!-- 测试环境记住密码 start😒-->
const isShowPassword = ref(true); // 是否展示密码
const isRemember = ref(false);
// <!-- 测试环境记住密码 start😒-->

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
// const dictsStore = useDictStore();
const keepAliveStore = useKeepAliveStore();
const env = ref(import.meta.env);

const propsData = defineProps<Props>();

type FormInstance = InstanceType<typeof ElForm>;

// 密码校验
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("密码不能为空"));
  } else if (loginForm.username === "") {
    // 解释一下为什么要判断用户名不能为空
    // 因为我们的密码校验其中有一项是要校验是否包含用户名，如果用户名不输入，怎么校验？？？

    callback(new Error("请先输入用户名"));
  } else {
    const finalCheckPwd =
      /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/;

    // 校验密码
    const checkPwd: boolean = finalCheckPwd.test(loginForm.password);

    if (!checkPwd) {
      callback(new Error("密码必须不少于8位, 包含大小写字母、数字、字符至少三种"));
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};

const loginFormRef = ref<FormInstance>();
const loginRules1 = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { required: true, trigger: "blur", validator: validatePass }
  ],
  verificationCode: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const loginRules2 = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: "",
  verificationKey: "",
  verificationCode: "",
  clientType: 1,
  isEncryption: 1
});

// 打开 drawer(新增、查看、编辑)
const dialogRef = ref<InstanceType<typeof ChangePasswordDialog> | null>(null);
const openDialog = (row: Partial<Login.ReqLoginForm> = {}) => {
  const params = {
    isView: false,
    row: { ...row }
  };
  dialogRef.value?.acceptParams(params);
};

const dynamicCode = ref("");
const getDynamicCode = async () => {
  if (env.value.VITE_RELEASE_NAME !== "fendi") return;
  const { data } = await getIdentify();
  dynamicCode.value = data.verificationCode;
  loginForm.verificationKey = data.verificationKey;
};

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      // const { data } = await loginApi({ ...loginForm, password: md5(loginForm.password) });
      const { data } = await loginApi({ ...loginForm, password: md5(loginForm.password) });
      if (data.needUpatePsw) {
        openDialog({ type: 2, userId: data.userId });
        return;
      }
      userStore.setToken(`${data.token.token_type} ${data.token.token}`);
      userStore.setUserInfo(data.sysUser);
      userStore.setStore(data.store);

      await isOutDate().then(res => {
        console.log(res);

        if (!(env.value.VITE_RELEASE_NAME == "fendi")) {
          userStore.setActivation(res.data);
        }
      });
      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.closeMultipleTab();
      keepAliveStore.setKeepAliveName();

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录!",
        type: "success",
        duration: 3000
      });
      //  <!-- 测试环境记住密码 start😒-->
      if (isShowPassword.value && isRemember.value) {
        localStorage.setItem("loginForm", JSON.stringify(loginForm));
      }
      //  <!-- 测试环境记住密码 start😒-->
    } finally {
      getDynamicCode();
      loading.value = false;
    }
  });
};

// resetForm
// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

onMounted(() => {
  //  <!-- 测试环境记住密码 start😒-->
  const info = localStorage.getItem("loginForm");
  if (isShowPassword.value && info) {
    const ls: Login.ReqLoginForm = JSON.parse(info);
    loginForm.password = ls.password;
    loginForm.username = ls.username;
    isRemember.value = true;
  }
  //  <!-- 测试环境记住密码 start😒-->

  getDynamicCode();
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../login.scss";
</style>
